package com.leetcode.p100;

import com.bean.TreeNode;
import com.utils.TreeUtils;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 二叉树的先序遍历
 */
public class Test102 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Deque<TreeNode> deque = new LinkedList();
        if (null == root) {
            return res;
        }

        deque.addLast(root);

        help(deque, res, 1);

        return res;
    }

    private void help(Deque<TreeNode> deque, List<List<Integer>> res, int size) {
        if (deque.size() <= 0) {
            return;
        }

        int currentSize = size;

        List<Integer> list = new ArrayList<>();
        while (currentSize > 0) {
            TreeNode node = deque.pollFirst();
            if (node.left != null) {
                deque.addLast(node.left);
            }

            if (node.right != null) {
                deque.addLast(node.right);
            }

            list.add(node.val);
            currentSize--;
        }

        res.add(list);
        help(deque, res, deque.size());
    }

    public static void main(String[] args) {
        TreeNode root = TreeUtils.buildTree();
        TreeUtils.showTree(root);

        Test102 test = new Test102();
        List result = test.levelOrder(root);
        System.out.println(result);
    }

}
